package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
//@Transactional
public class UserInfoServiceImpl implements IUserInfoService {

    /*@Value("${sms.url}")
    private String url;

    @Value("${sms.appkey}")
    private String appkey;*/

    @Autowired
    private UserInfoRepository repository;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void save(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return repository.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {

        UserInfo userInfo = repository.findByPhone(phone);
        return userInfo != null;
    }

    @Override
    public void sendVerifyCode(String phone) {

        //创建验证码
        String code = UUID.randomUUID().toString()
                .replaceAll("-","")
                .substring(0,4);

        //创建短信
        StringBuilder sb = new StringBuilder(80);
        sb.append("【创信】您的短信验证码是:").append(code)
                .append(" ,请在").append(Consts.VERIFY_CODE_VAI_TIME)
                .append("分钟内使用");

        System.out.println(sb);

        //真实短信发送 本质就是使用java发起http请求即可
        //Springmvc提供一个工具类:RestTemplate,用于发起https请求
        //RestTemplate template = new RestTemplate();

        //参数1: 短信接口url
        //09:41:16
        //Url:https://way.jd.com/chonry/smsapi?sign=【创瑞云】&mobile=17755324095&content=您的本次的验证码是：0086。&appkey=343c12d13900a9f688425fb304b79ee2
        //String url = "https://way.jd.com/chonry/smsapi?sign=【创瑞云】&mobile={1}&content={2}&appkey={3}";
        //参数2:请求接口完之后相应数据封装对象类型
        //参数3:请求参数列表
        /*String ret = template.getForObject(url,String.class,phone,sb.toString(),appkey);
        System.out.println(ret);

        if (!ret.contains("Success")){
            throw new LogicException("短信发送失败");
        }*/
        //将验证码存入redis中
        userInfoRedisService.setVerifyCode(phone,code);
    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {

        //效验参数是否为空
        AssertUtil.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");

        //验证两次输入的密码是否一致
        AssertUtil.isEquals(password,rpassword,"两次输入的密码不一致");

        //验证手机号码是否正确,java的正则表达式
        Pattern p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$");
        Matcher m = p.matcher(phone);
        if (!m.matches()){
            throw new LogicException("该手机号码不规范");
        }

        //验证手机号码是否已经被注册
        if (this.checkPhone(phone)){
            throw  new LogicException("该手机号已被注册");
        }

        //验证短信验证码是否一致
        String code = userInfoRedisService.getVerifyCode(phone);

        if (!verifyCode.equalsIgnoreCase(code)){
            throw new LogicException("验证码输入有误");
        }

        //注册,添加注册信息
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname); //昵称
        userInfo.setPhone(phone); //手机号码
        userInfo.setEmail(""); //email
        userInfo.setPassword(password); //密码
        userInfo.setLevel(1); //等级
        userInfo.setCity(""); //城市
        userInfo.setInfo("");
        userInfo.setHeadImgUrl("images/default.jpg");

        //核心属性必须自己控制
        userInfo.setState(UserInfo.STATE_NORMAL);

        //保存用户注册信息
        this.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {

        UserInfo user = repository.findByPhoneAndPassword(username,password);
        if (user == null || !user.getPassword().equals(password)){
            throw new LogicException("账号和密码错误");
        }
        //隐藏密码
        user.setPassword("");
        return user;
    }

}
